<!-- eslint-disable vue/no-template-shadow -->
<!--
 * @Description: 数据项管理页面
-->
<template>
  <BaseMainSlot>
    <!-- <template v-slot:farmtypeselectslot> -->
    <!-- </template> -->
    <template v-slot:btn-box>
      <ActionBar
        :page-no="103"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-edit="false"
        :has-save="false"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save('formData')"
      />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <SelectButton
          :buttonselectlist="buttonselectlist"
          @topitemtype="topitemtype"
        />
        <div class="common-search-item">
          <!-- <div class="label">部门:</div>
          <div class="input">
            <el-select
              v-model="departmentNo"
              placeholder="请选择部门"
              filterable
              clearable
              @change="departmentPost"
            >
              <el-option
                v-for="item in departmentList"
                :key="item.departmentNo"
                :label="item.departmentName"
                :value="item.departmentNo"
              />
            </el-select>
          </div> -->
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @row-click="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="selectable" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column
          prop="originalName"
          label="数据项名称"
          min-width="120"
        />
        <el-table-column prop="dataItemName" label="展示数据名称" />
        <el-table-column
          prop="visible"
          label="是否可展示"
        >
          <template v-if="scope.row.category" slot-scope="scope">
            <span v-if="scope.row.visible">
              可展示
            </span>
            <span v-if="!scope.row.visible">
              不可展示
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="control"
          label="是否可控"
        >
          <template v-if="scope.row.category" slot-scope="scope">
            <span v-if="scope.row.control">
              可控
            </span>
            <span v-if="!scope.row.control">
              不可控
            </span>
          </template>
        </el-table-column>
        <el-table-column width="200" label="操作">
          <template v-if="scope.row.dataItemId" slot-scope="scope">
            <el-button v-if="judgePermission(103, 'edit')" class="text-btn-cursor" type="text" size="small" @click="edit"><i class="el-icon-edit-outline"></i> 修改</el-button>
            <el-button v-if="judgePermission(103, 'delete')" class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete(scope.row.dataItemId)"><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText + '数据项信息'"
        :visible.sync="dialogFormVisible"
        @close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item v-if="topitemType =='ATMOSPHERE'" label="选择气象站:" prop="dataItemId" class="w50p">
            <el-select
              v-model="formData.rtuId"
              placeholder="请选择气象站"
              :disabled="!canInput"
              filterable
              clearable
              @change="MeteorologicalItem"
            >
              <el-option
                v-for="item in MeteorologicalList"
                :key="item.rtuId"
                :label="item.rtuName"
                :value="item.rtuId"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="topitemType !=='ATMOSPHERE'" label="选择工程项目:" prop="rtuNo" class="w50p">
            <el-cascader
              :options="options"
              :props="{ expandTrigger: 'hover',value: 'companyMark',children:'child',label:'ownershipName', checkStrictly: true, }"
              clearable
              @change="ownership"
            />
          </el-form-item>
          <el-form-item label="数据项选择:" prop="dataItemId" class="w50p">
            <el-select
              v-model="formData.dataItemId"
              placeholder="请选择数据项"
              :disabled="!canInput"
              filterable
              clearable
              @change="depDataItem"
            >
              <el-option
                v-for="item in dataItemList"
                :key="item.dataItemId"
                :label="item.dataItemName"
                :value="item.dataItemId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="展示数据项名称:" prop="dataItemName" class="w50p">
            <el-input
              v-model="formData.dataItemName"
              placeholder=""
              clearable
            />
          </el-form-item>
          <el-form-item label="原始名称:" prop="originalName" class="w50p">
            <el-input
              v-model="formData.originalName"
              placeholder=""
              disabled
              clearable
            />
          </el-form-item>
          <el-form-item label="是否可展示:" prop="visible" class="w50p">
            <el-select
              v-model="formData.visible"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
              <!-- <el-option label="无" value="无" /> -->
            </el-select>
          </el-form-item>
          <el-form-item label="是否可控:" prop="control" class="w50p">
            <el-select
              v-model="formData.control"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            <!-- <el-option label="无" value="无" /> -->
            </el-select>
          </el-form-item>
          <el-form-item
            label="单位:"
            prop="identificationNumber"
            class="w50p"
          >
            <el-select
              v-model="formData.unitNo"
              placeholder="请选择单位"
              filterable
              clearable
            >
              <el-option
                v-for="item in unitList"
                :key="item.unitNo"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import dataItem from "@/api/basic-info-manage/data-item-management.js";
import SelectButton from "./selectbutton";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from 'vuex';
import Axios from "axios";

export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "dataItemManagement",
  components: { Pagination, SelectButton, BaseMainSlot, SearchBox, ActionBar },
  mixins: [mymixin],
  data() {
    return {
      obj: {
        name: ""
      },
      buttonselectlist: [
        {
          name: "空气数据",
          type: "AIR"
        },
        {
          name: "告警指示灯数据",
          type: "ALARM"
        },
        {
          name: "气象站API",
          type: "ATMOSPHERE"
        },
        {
          name: "土壤数据",
          type: "SOIL"
        },
        {
          name: "设备状态",
          type: "STATE"
        },
        {
          name: "大田气象站数据",
          type: "WEATHER"
        }
      ],
      dataItemList: [],
      unitList: [],
      //  标签栏相关
      activeName: "first",
      rules: {},
      // 选中的设施id数组 ID组成
      incomeCostIdList: [],
      // 柱状图相关值
      bottomtabdat: {},
      dialogFormVisible: false,
      tabtype: false,
      agriculturalWorkType: {},
      batchVo: {},
      facilityVoList: [],
      MeteorologicalList: [],
      scope: "",
      startTime: "",
      endTime: "",
      topitemType: "",
      dataTreeItemList: [],
      options: []
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 获取表格数据
    this.getSelectlist();
  },
  mounted() {},
  methods: {
    selectable (row) {
      console.log(row)
      return !('index' in row)
    },
    topitemtype(e) {
      this.topitemType = e;
      // 获取表格数据
      this.tableData = [];
      this.getTableDataList();
    },
    // 标签栏相关方法
    // 获取表格数据
    getTableDataList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          category: this.topitemType,
          organizationNo: sessionStorage.organizationNo,
          startTime: this.startTime,
          endTime: this.endTime
        }
      };
      dataItem.dataItemlist(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    async getSelectlist() {
      // dataItem
      //   .getDataItemByList({ farmingTypeNo: this.topitemtypeid })
      //   .then(res => {
      //     let data = res.data;
      //     this.dataItemList = data;
      //   });
      Axios({
        url: this.$cloudBaseurl + `ownership/queryTreeByCompanyMark?companyMark=${sessionStorage.organizationNo}`,
        method: "get"
      }).then((res) => {
        if (res.data.code === 1) {
          // this.getTableDataList();
          this.dataTreeItemList = [res.data.data];
          // console.log(res.data)
          this.options = this.filterArrForKey([res.data.data])
          this.dialogFormVisible = false;
          // this.$message.success("查询成功！");
        } else {
          this.$message.warning("查询失败！");
        }
      })
      dataItem.getPlantingUnitListByCondition()
        .then(res => {
          let data = res.data;
          this.unitList = data;
        });

      dataItem.getMeteorologicalByCondition()
        .then(res => {
          let data = res.data;
          this.MeteorologicalList = data;
        });
    },
    ownership(e) {
      // console.log(e)
      if (e) {
        let text = e.slice(-1)
        // console.log(text[0])
        dataItem
          .getDataItemByList(text[0])
          .then(res => {
            let data = res.data;
            this.dataItemList = data;
            this.$set(this.formData, 'rtuNo', '')
            this.$set(this.formData, 'deviceName', '')
          });
      }
    },
    // owship(e) {
    //   dataItem
    //     .getDataItemByList(sessionStorage.organizationNo)
    //     .then(res => {
    //       let data = res.data;
    //       this.dataItemList = data;
    //       this.$set(this.formData, 'rtuNo', '')
    //       this.$set(this.formData, 'deviceName', '')
    //     });
    // },
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = []
      if (arr === []) {
        return
      }
      newArr = arr.map(item => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(
              item.child
            )
          }
        } else {
          delete item.child
        }
        return item
      })
      newArr = newArr.filter(item => item != null)
      return newArr
    },
    dateFormat(row, colnum) {
      return this.$moment(row[colnum.property]).format("YYYY-MM-DD");
    },
    operation(row) {
      if (row.agriculturalTaskId) {
        this.formData = {};
        this.operationVisible = true;
        this.formData.agriculturalWorkTypeName =
          row.agriculturalWorkType.agriculturalWorkTypeName;
        this.formData = row;
      }
    },
    // 搜索框时间
    startVal(e) {
      this.startTime = e;
    },
    endVal(e) {
      this.endTime = e;
    },
    MeteorologicalItem(e) {
      dataItem.getRtuByCondition(e).then(res => {
        this.dataItemList = res.data
      })
    },
    depDataItem(e) {
      let index = this.dataItemList.findIndex(
        (b) => b.dataItemId === e
      )
      let form = { ...this.dataItemList[index] }
      // console.log(form)
      this.$set(this.formData, 'category', this.topitemType)
      this.$set(this.formData, 'dataItemName', form.dataItemName)
      this.$set(this.formData, 'dataTypeId', form.dataTypeId)
      this.$set(this.formData, 'dataTypeName', form.dataType.dataTypeName)
      this.$set(this.formData, 'mainingControlType', form.dataType.mainingControlType)
      this.$set(this.formData, 'enumListType', form.dataType.enumListType)
      this.$set(this.formData, 'originalName', form.dataItemName)
      // this.formData
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    handleEdit(row) {
      // TODO 点击行元素后 edit
      this.formData = JSON.parse(JSON.stringify(row));
      // console.log(this.scope);
      this.editActive = true;
      this.saveActive = false;
      this.cancelActive = true;
      this.canInput = false;
    },
    handleSelectionChange(list) {
      this.incomeCostIdList = [];
      this.incomeCostIdList = list.map(item => item.dataItemId);
      if (this.incomeCostIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      dataItem.delListFarmingTypelist({ dataItemIdList: this.incomeCostIdList, organizationNo: sessionStorage.organizationNo }).then(res => {
        if (res.code === 1) {
          this.$message.success(res.msg);
          this.getTableDataList();
        } else {
          this.$message.warning(res.msg || "删除失败");
        }
      });
    },
    handleDelete(val) {
      // dataItem.delFarmingTypelist(val).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.getTableDataList();
      //   } else {
      //     this.$message.warning(res.msg || "删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          dataItem.delFarmingTypelist(val).then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
      // this.selectedStaffList.splice(0, this.selectedStaffList.length - 1);
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            // 巡检点数组赋值进formData
            dataItem.editFarmingTypelist(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                // this.postId = "";
                this.getTableDataList();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            this.formData.organizationNo = sessionStorage.organizationNo
            dataItem.addFarmingTypelist(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                // this.postId = "";
                this.getTableDataList();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";
::v-deep .el-dialog {
  height: 60%;
  .el-dialog__body {
    overflow-y: auto;
  }
  .el-input__inner {
    // background-color: rgba($color: #000000, $alpha: 0) !important;
    border: none !important;
  }
}
::v-deep .common-layout {
  width: calc(100% - 1px) !important;
  .zhcontent {
    position: relative;
    height: calc(100% - 100px) !important;
    .pagination {
      right: 0px !important;
    }
  }
}
</style>
